using System;
using System.Collections.Generic;
using System.Text;
using Csla;
using System.Data.Odbc;
using MinaspetroLibrary.Configuracoes;
using System.Data;
using Csla.Data;

namespace MinaspetroLibrary.NoticiasPack
{
    [Serializable()]
    public class NoticiaAnoNameValueList : NameValueListBase<string, string>
    {
        #region Factory Methods
        private NoticiaAnoNameValueList()
        { /* require use of factory method */ }

        public static NoticiaAnoNameValueList GetNoticiaAnoNameValueList()
        {
            return DataPortal.Fetch<NoticiaAnoNameValueList>(new FilterCriteria());
        }

        public static NoticiaAnoNameValueList GetNoticiaAnoNameValueList(string inicial)
        {
            return DataPortal.Fetch<NoticiaAnoNameValueList>(new FilterCriteria(inicial));
        }
        #endregion //Factory Methods

        #region Data Access
        class FilterCriteria
        {
            public string Inicial = string.Empty;

            public FilterCriteria()
            {
            }

            public FilterCriteria(string inicial)
            {
                this.Inicial = inicial;
            }
        }

        private void DataPortal_Fetch(FilterCriteria criteria)
        {
            RaiseListChangedEvents = false;

            using (OdbcConnection cn = new OdbcConnection(ConfigDatabase.MinaspetroConnection))
            using (OdbcCommand cm = cn.CreateCommand())
            {
                IsReadOnly = false;
                cn.Open();

                cm.CommandType = CommandType.Text;
                cm.CommandText = "SELECT distinct(year(data)) ano from noticiatb order by ano ASC ;";


                if (criteria.Inicial != string.Empty)
                    this.Add(new NameValuePair("0", criteria.Inicial));

                using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
                {
                    while (dr.Read())
                        this.Add(new NameValuePair(dr["ano"].ToString(), dr["ano"].ToString()));
                }
                IsReadOnly = true;
            }//using

            RaiseListChangedEvents = true;
        }
        #endregion //Data Access
    }
}
